// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  
  try {
    const {
      dishName,
      cookingTime,
      ingredients,
      steps,
      photos,
      difficulty
    } = event

    // 数据验证
    if (!dishName || !cookingTime || photos.length === 0) {
      return {
        success: false,
        error: '缺少必要信息'
      }
    }

    // 添加记录
    const result = await db.collection('cooking').add({
      data: {
        dishName,
        cookingTime,
        ingredients,
        steps,
        photos,
        difficulty,
        openid: wxContext.OPENID,
        createTime: db.serverDate(),
        updateTime: db.serverDate()
      }
    })

    // 更新食材使用频率
    if (ingredients && ingredients.length > 0) {
      const ingredientTasks = ingredients.map(ingredient => 
        db.collection('foods').where({
          name: ingredient.name
        }).update({
          data: {
            useCount: db.command.inc(1)
          }
        })
      )
      await Promise.all(ingredientTasks)
    }

    return {
      success: true,
      data: result._id
    }

  } catch (err) {
    console.error('[addCookingRecord] 错误:', err)
    return {
      success: false,
      error: err.message
    }
  }
} 